package net.worldscale.xp.wslib.urm;

import java.util.Hashtable;

final class ImplAppManager extends AppManager {

    private final Hashtable<String, IAppLoader> mTable = new Hashtable<String, IAppLoader>();

    public ImplAppManager() {
    }

    @Override
    public void regAppLoader(IAppLoader appLoader) {
        appLoader.regSelf(this);
    }

    @Override
    public void regAppLoader(IAppLoader app, String mime) {
        if ((app != null) && (mime != null)) {
            if (app.isSupport(mime)) {
                mTable.put(mime, app);
            }
        }
    }

    @Override
    public IAppLoader getAppLoader(String mime) {
        if (mime != null) {
            final int i = mime.indexOf(';');
            if (0 <= i) {
                mime = mime.substring(0, i);
            }
        }
        return mTable.get(mime);
    }

    @Override
    public IApp open(final Resource res) {
        if (res == null) {
            return null;
        }
        final String mime = res.getMimeType();
        final IAppLoader ldr = this.getAppLoader(mime);
        if (ldr == null) {
            return null;
        }
        return ldr.open(res);
    }

    @Override
    public Resource open(String uri) {
        final Sandbox sb = new ImplSandbox(uri);
        return sb.getMainResource();
    }

    @Override
    public void openAuto(String uri) {
        final Resource res = this.open(uri);
        final ISandboxListener l = new ISandboxListener() {

            @Override
            public void onLoadingFinish(Resource res) {
            }

            @Override
            public boolean onMimeType(Resource res, String mime) {
                final IAppLoader appldr = URM.getInstance().getAppManager().getAppLoader(mime);
                if (appldr == null) {
                    return false;
                }
                appldr.open(res);
                return true;
            }
        };
        res.getOwnerSandbox().setListener(l);
        res.load();
    }
}
